# 作者 :南雨
# 时间 : 2022/6/26 6:46
import tensorflow as tf
from dzj.med_qa.med_w2vec import get_test
from tensorflow.keras.preprocessing.sequence import pad_sequences
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score, recall_score, f1_score
from dzj.med_qa.med_constant import Med_constant
import dzj.med_qa.med_processing as prs
import numpy as np

test_X, test_y, dict_word = get_test()


def text_to_sequence(texts):
    sentence = prs.find_chinese(texts)
    text_list = prs.cut_word(sentence)
    word_list = prs.remove_stopwords(text_list)
    res_text = []
    for word in word_list:
        if word in dict_word.keys():
            res_text.append(dict_word[word])
        else:
            res_text.append(0)
    res_text = pad_sequences([res_text], maxlen=Med_constant.max_len, padding='post', truncating='post')

    return res_text


def predict(text):
    model = tf.keras.models.load_model(Med_constant.med_model_path, compile=False)
    y_pred = model.predict(test_X)
    y_pred = np.argmax(y_pred, axis=1)
    y_true = np.argmax(test_y, axis=1)

    precision = precision_score(y_true, y_pred, average='weighted')
    recall = recall_score(y_true, y_pred, average='weighted')
    f1 = f1_score(y_true, y_pred, average='weighted')

    text_pred = model.predict(text_to_sequence(text))
    text_label = np.argmax(text_pred, axis=1)[0]

    result = get_key(text_label)
    return result, '%.3f' % precision, '%.3f' % recall, '%.3f' % f1


def get_key(val):
    for key, value in Med_constant.category_dict.items():
        if val == value:
            return key

    return "无法识别"

#
# text = "无痛胃镜与普通胃镜区别"
# print(predict(text))
